package com.hulman.oms.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.hulman.oms.bean.ElectricMeter;
import com.hulman.oms.bean.ElectricReportItem;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.ElectricReport;
import com.hulman.oms.dao.ElectricMeterDao;
import com.hulman.oms.dao.ElectricReportDao;
import com.hulman.oms.dao.ElectricReportItemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class ElectricReportService
{
    @Autowired
    private ElectricReportDao electricReportDao;
    @Autowired
    private ElectricMeterService electricMeterService;
    @Autowired
    private ElectricReportItemDao electricReportItemDao;
    @Autowired
    private ElectricReportItemService electricReportItemService;

    public List<ElectricReport> findElectricReports(Map<String, Object> map)
    {
        return electricReportDao.findElectricReports(map);
    }

    public Integer findElectricReportsCount(Map<String, Object> map)
    {
        return electricReportDao.findElectricReportsCount(map);
    }

    public Result findElectricReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = electricReportDao.findElectricReportsCount(map);
        List<ElectricReport> data = electricReportDao.findElectricReports(map);
        return new Result(data, count);
    }

    public ElectricReport findElectricReportById(Integer id)
    {
        return electricReportDao.findElectricReportById(id);
    }

    public void saveElectricReport(ElectricReport electricReport)
    {
        if (electricReport.getId() != null && electricReport.getId() != 0)
        {
            electricReportDao.updateElectricReport(electricReport);
        } else
        {
            electricReportDao.insertElectricReport(electricReport);
        }
    }

    public void deleteElectricReportById(Integer id)
    {
        electricReportDao.deleteElectricReportById(id);
    }

    public void deleteElectricReports(int[] ids)
    {
        electricReportDao.deleteElectricReports(ids);
    }

    /**
     * 创建报表
     *
     * @param report
     */
    @Transactional(rollbackFor = Exception.class)
    public void createReport(ElectricReport report)
    {
        electricReportDao.insertElectricReport(report);
        List<ElectricMeter> meters = electricMeterService.findAllElectricMeters();
        for (ElectricMeter meter : meters)
        {
            ElectricReportItem item = new ElectricReportItem();
            item.setReportId(report.getId());
            item.setMeterId(meter.getId());
            item.setMeterName(meter.getName());
            item.setMeterNo(meter.getNo());
            item.setRatio(meter.getRatio());
            item.setLastAmount(meter.getAmount());
            item.setLastBalance(meter.getBalance());
            item.setState(0);
            electricReportItemDao.insertElectricReportItem(item);
        }
    }

    /**
     * 导出报表
     * @param id
     * @param outputStream
     * @throws IOException
     */
    public void exportElectricReports(Integer id, OutputStream outputStream) throws IOException
    {
        ElectricReport report = electricReportDao.findElectricReportById(id);
        List<ElectricReportItem> items = electricReportItemService.findElectricReportItemsByReportId(id);
        Integer totalAmount = 0;
        Integer totalCost = 0;
        Integer sn = 1;
        for (ElectricReportItem item : items)
        {
            item.setSn(sn++);
            if (item.getWeeklyAmount() != null)
            {
                totalAmount += item.getWeeklyAmount();
            }
            if (item.getWeeklyCost() != null)
            {
                totalCost += item.getWeeklyCost();
            }
        }
        report.setTotalAmount(totalAmount);
        report.setTotalCost(totalCost);
        InputStream inputStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("template/electric-report.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(items, fillConfig, writeSheet);
        excelWriter.fill(report, writeSheet);
        excelWriter.finish();
    }

}
